<template>
  <view class="search-bar-container">
    <!-- 搜索框 -->
    <view class="search-box" @tap="showSearch = true">
      <uni-icons type="search" size="18" color="#999"></uni-icons>
      <text class="search-placeholder">{{ placeholder }}</text>
    </view>

    <!-- 搜索弹窗 -->
    <view v-if="showSearch" class="search-modal">
      <view class="modal-header">
        <view class="search-input-box">
          <uni-icons type="search" size="18" color="#999"></uni-icons>
          <input 
            v-model="keyword" 
            class="search-input"
            :placeholder="placeholder"
            :focus="true"
            @input="onSearchInput"
            @confirm="onSearchConfirm"
          />
          <uni-icons 
            v-if="keyword" 
            type="clear" 
            size="18" 
            color="#999"
            @tap="clearSearch"
          ></uni-icons>
        </view>
        <text class="cancel-btn" @tap="closeSearch">取消</text>
      </view>

      <!-- 搜索历史 -->
      <view v-if="searchHistory.length > 0 && !keyword" class="search-history">
        <view class="history-header">
          <text class="history-title">搜索历史</text>
          <uni-icons type="trash" size="20" color="#999" @tap="clearHistory"></uni-icons>
        </view>
        <view class="history-list">
          <view 
            v-for="(item, index) in searchHistory" 
            :key="index"
            class="history-item"
            @tap="selectHistory(item)"
          >
            <uni-icons type="clock" size="16" color="#999"></uni-icons>
            <text class="history-text">{{ item }}</text>
          </view>
        </view>
      </view>

      <!-- 搜索结果 -->
      <scroll-view v-if="keyword" class="search-results" scroll-y>
        <!-- 商家结果 -->
        <view v-if="merchantResults.length > 0" class="result-section">
          <text class="result-title">商家</text>
          <view 
            v-for="merchant in merchantResults" 
            :key="merchant.id"
            class="result-item merchant-item"
            @tap="selectMerchant(merchant)"
          >
            <image :src="merchant.logo" class="merchant-logo"></image>
            <view class="merchant-info">
              <text class="merchant-name">{{ merchant.name }}</text>
              <text class="merchant-desc">{{ merchant.tags.join(' · ') }}</text>
            </view>
            <uni-icons type="arrowright" size="16" color="#ccc"></uni-icons>
          </view>
        </view>

        <!-- 商品结果 -->
        <view v-if="productResults.length > 0" class="result-section">
          <text class="result-title">商品</text>
          <view 
            v-for="product in productResults" 
            :key="product.id"
            class="result-item product-item"
            @tap="selectProduct(product)"
          >
            <image :src="product.image" class="product-image"></image>
            <view class="product-info">
              <text class="product-name">{{ product.name }}</text>
              <text class="product-price">¥{{ product.price }}</text>
            </view>
            <uni-icons type="arrowright" size="16" color="#ccc"></uni-icons>
          </view>
        </view>

        <!-- 空状态 -->
        <view v-if="merchantResults.length === 0 && productResults.length === 0" class="empty-state">
          <uni-icons type="search" size="60" color="#ccc"></uni-icons>
          <text class="empty-text">暂无搜索结果</text>
        </view>
      </scroll-view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue';

const props = defineProps({
  placeholder: {
    type: String,
    default: '搜索商家、商品'
  }
});

const emit = defineEmits(['selectMerchant', 'selectProduct']);

const showSearch = ref(false);
const keyword = ref('');
const searchHistory = ref<string[]>([]);
const merchantResults = ref<any[]>([]);
const productResults = ref<any[]>([]);

let searchTimer: any = null;

// 加载搜索历史
const loadSearchHistory = () => {
  const history = uni.getStorageSync('searchHistory') || [];
  searchHistory.value = history;
};

// 搜索输入
const onSearchInput = () => {
  // 防抖处理
  if (searchTimer) {
    clearTimeout(searchTimer);
  }
  
  searchTimer = setTimeout(() => {
    performSearch();
  }, 500);
};

// 执行搜索
const performSearch = async () => {
  if (!keyword.value.trim()) {
    merchantResults.value = [];
    productResults.value = [];
    return;
  }
  
  try {
    // TODO: 调用后端搜索接口
    // 这里先用模拟数据
    merchantResults.value = [
      {
        id: 1,
        name: '绿光餐厅',
        logo: '/static/shangjia01.png',
        tags: ['日料', '快餐']
      }
    ];
    
    productResults.value = [
      {
        id: 1,
        name: '香辣鸡腿饭',
        image: '/static/food01.png',
        price: 23.0,
        merchantId: 1
      }
    ];
  } catch (error) {
    console.error('搜索失败:', error);
  }
};

// 搜索确认
const onSearchConfirm = () => {
  performSearch();
  saveSearchHistory();
};

// 保存搜索历史
const saveSearchHistory = () => {
  if (!keyword.value.trim()) return;
  
  let history = uni.getStorageSync('searchHistory') || [];
  
  // 移除重复项
  history = history.filter((item: string) => item !== keyword.value);
  
  // 添加到开头
  history.unshift(keyword.value);
  
  // 最多保留10条
  if (history.length > 10) {
    history = history.slice(0, 10);
  }
  
  uni.setStorageSync('searchHistory', history);
  searchHistory.value = history;
};

// 选择历史记录
const selectHistory = (item: string) => {
  keyword.value = item;
  performSearch();
};

// 清除搜索
const clearSearch = () => {
  keyword.value = '';
  merchantResults.value = [];
  productResults.value = [];
};

// 清除历史
const clearHistory = () => {
  uni.showModal({
    title: '提示',
    content: '确定要清除搜索历史吗?',
    success: (res) => {
      if (res.confirm) {
        uni.removeStorageSync('searchHistory');
        searchHistory.value = [];
      }
    }
  });
};

// 关闭搜索
const closeSearch = () => {
  showSearch.value = false;
  clearSearch();
};

// 选择商家
const selectMerchant = (merchant: any) => {
  saveSearchHistory();
  emit('selectMerchant', merchant);
  closeSearch();
};

// 选择商品
const selectProduct = (product: any) => {
  saveSearchHistory();
  emit('selectProduct', product);
  closeSearch();
};

// 监听显示状态,加载历史
watch(showSearch, (newVal) => {
  if (newVal) {
    loadSearchHistory();
  }
});
</script>

<style scoped>
.search-bar-container {
  position: relative;
}

.search-box {
  display: flex;
  align-items: center;
  background-color: #f5f5f5;
  border-radius: 30rpx;
  padding: 18rpx 30rpx;
  gap: 15rpx;
}

.search-placeholder {
  font-size: 28rpx;
  color: #999;
}

.search-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #fff;
  z-index: 999;
}

.modal-header {
  display: flex;
  align-items: center;
  padding: 20rpx 30rpx;
  border-bottom: 1rpx solid #f0f0f0;
  gap: 20rpx;
}

.search-input-box {
  flex: 1;
  display: flex;
  align-items: center;
  background-color: #f5f5f5;
  border-radius: 30rpx;
  padding: 15rpx 25rpx;
  gap: 15rpx;
}

.search-input {
  flex: 1;
  font-size: 28rpx;
  color: #333;
}

.cancel-btn {
  font-size: 28rpx;
  color: #666;
}

.search-history {
  padding: 30rpx;
}

.history-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
}

.history-title {
  font-size: 28rpx;
  color: #333;
  font-weight: bold;
}

.history-list {
  display: flex;
  flex-wrap: wrap;
  gap: 20rpx;
}

.history-item {
  display: flex;
  align-items: center;
  gap: 10rpx;
  padding: 15rpx 25rpx;
  background-color: #f5f5f5;
  border-radius: 30rpx;
}

.history-text {
  font-size: 26rpx;
  color: #666;
}

.search-results {
  height: calc(100vh - 120rpx);
  padding: 0 30rpx;
}

.result-section {
  margin-bottom: 30rpx;
}

.result-title {
  display: block;
  font-size: 28rpx;
  color: #999;
  margin: 20rpx 0;
}

.result-item {
  display: flex;
  align-items: center;
  padding: 20rpx 0;
  border-bottom: 1rpx solid #f0f0f0;
}

.merchant-item {
  gap: 20rpx;
}

.merchant-logo {
  width: 100rpx;
  height: 100rpx;
  border-radius: 12rpx;
}

.merchant-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 8rpx;
}

.merchant-name {
  font-size: 30rpx;
  color: #333;
  font-weight: bold;
}

.merchant-desc {
  font-size: 24rpx;
  color: #999;
}

.product-item {
  gap: 20rpx;
}

.product-image {
  width: 100rpx;
  height: 100rpx;
  border-radius: 12rpx;
}

.product-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 8rpx;
}

.product-name {
  font-size: 28rpx;
  color: #333;
}

.product-price {
  font-size: 28rpx;
  color: #ff3b30;
  font-weight: bold;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 200rpx 0;
}

.empty-text {
  font-size: 28rpx;
  color: #999;
  margin-top: 20rpx;
}
</style>